package com.one.blocks.rbac.manager;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author <a href="mailto:idler41@163.com">linfuxin</a> created by 2022-05-01 13:54:01
 */
@Component
public class PasswordManager implements InitializingBean {

    @Value("${app.blocks.security.authc.login.private-key}")
    private String privateKey;

    @Autowired
    private PasswordEncoder passwordEncoder;

    private RSA rsa;

    @Override
    public void afterPropertiesSet() throws Exception {
        rsa = new RSA(privateKey, null);
    }

    public String decryptPassword(String password) {
        return rsa.decryptStr(password, KeyType.PrivateKey);
    }

    public boolean match(String loginPassword, String dbPassword) {
        return dbPassword != null && passwordEncoder.matches(loginPassword, dbPassword);
    }

    public String encode(String text) {
        return passwordEncoder.encode(text);
    }

    public static void main(String[] args) {
        String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANqpjAKuHZ/uGKm8q26fjcKHZTVMT7rbkJTKNKGjzaZ/B4PkcVBu3Ca6IzVt8+EdaskbZQah4Qjb1fGV+4s/w+ySa6bESR/8dVwge1TXTD591zA9Vnao6gVYP0qM8QECwhKyUZKo6cRbjJuDPP4PIBBo7tIMINCi2bHVUtRgFHBBAgMBAAECgYEAp3RCWecXntvLHWn0a3JbMMdZlZiMUpBFR/0Wk1cLbd9IVRRERxGvHSVdQ1Sh+Rr7JWoKUyrzWEJqtGlkyv4ZPo8/5lZV9RmBOSETUyOzyxWXdGrQwoATNhyxqz/TKcpag5qfr67f9CgaeOjPwa/tLsoiaYkve6aWbAMQXpwwdcUCQQD1ZLL/NEaErw2vcRCuCWUap55+01dRtoYEQhjGp/SuPRJKlFJQoIv8DyZbxyjMpydZDQndVpYSF1oVhPGfWEzjAkEA5B0Q4jCTJFNBpwyfJxvlZH/B9wrlmKJ5B3gbVDC62o3/3SVpXKtc7KohMeH8dIgLsb33Zac34ITLX/2J0FpbiwJAWQpk+L0bKWHrcVFxX/UAvp87n4FIGdpE3p6tJsgivGZkkLMo+yCGKrvEi2DEqR2t5V4Zyjp00bOveEd49PyxSQJBAJrKGmXSHlac5ETtrKWGKW+7vavcShX70fK+jpTfiDu79a5jr45BfgneHC5UMdIFayIOTO0+vgztL3AQhE7MsacCQQDhzHvAr7PA9KQFQ63lpkW+8laMJZToHHm8Qmfegft5lqQF/5XUAT4Y3iBUH8JqoZrIwpYxiIWzn0JQyKqPvhaG";
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDaqYwCrh2f7hipvKtun43Ch2U1TE+625CUyjSho82mfweD5HFQbtwmuiM1bfPhHWrJG2UGoeEI29XxlfuLP8PskmumxEkf/HVcIHtU10w+fdcwPVZ2qOoFWD9KjPEBAsISslGSqOnEW4ybgzz+DyAQaO7SDCDQotmx1VLUYBRwQQIDAQAB";
        RSA test = new RSA(privateKey, publicKey);
        // RTSuP1WYvtS0gMjmnKGcQyA06hlqjKGT+xs7fLlqJPhcVpxYci/h7oY905ksCUMA+o0oyE3Nj/W8U13istLJmTUImn4MbI3YZVfLPCqgJTwpVxTY1KZLxcaxffLsHu27YVKEJ0NdeaVeDam/eRsrSBp9IyD6CErHoibFzMfPG04=
        String password = test.encryptBase64("123456", KeyType.PublicKey);
        String rawPassword = test.decryptStr(password, KeyType.PrivateKey);
        System.out.println(password);
        System.out.println(rawPassword);
    }
}
